package cn.huyanbing.middleware.trace.reflect;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

/**
 * @BelongProject middleware
 * @BelongPackage cn.huyanbing.middleware.trace.reflect
 * @Description TODO
 * @ClassName Transformer
 * @Author huyangbing
 * @Date 2024/8/30 15:44
 * @Version 1.0.0
 */
public class Transformer implements ClassFileTransformer {


    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain, byte[] classfileBuffer)
            throws IllegalClassFormatException {

        System.out.println("transform()");

        if (className.equalsIgnoreCase("cn.huyanbing.middleware.trace.reflect.TransClass")) {

            ClassPool classPool = ClassPool.getDefault();

            try {

                CtClass ctClass = classPool.get(className.replaceAll("/", "."));
                CtMethod ctMethod = ctClass.getDeclaredMethod("sayHello");

                if (!ctMethod.isEmpty()) {
                    ctMethod.insertBefore("System.out.println(\\\"before hello!!!\\\");");
                }
                return ctClass.toBytecode();

            } catch (Exception e) {

                e.printStackTrace();
            }
        }

        return null;

    }

}
